require 'pop_ssl' # it's the same as ruby 1.9 pop.rb, 1.8 doesn't do SSL

class MailHandler < ActionMailer::Base
  
  def self.check_mail
    retrycount = 0
    email_queue =[]
    begin
      Net::POP3.enable_ssl(OpenSSL::SSL::VERIFY_NONE) if POP_SSL #note it's a class method
      timeout(600) do
        Net::POP3.start(POP_ADDR, POP_PORT, POP_USERNAME, POP_PASSWORD) do |pop|
          if pop.mails.empty?
            #logger.info "NO MAIL"
          else
            pop.mails.each do |email|
              begin
                #logger.info "receiving mail..."
                email_queue << self.receive(email.pop)
                #email.delete
              rescue Exception => e
                #logger.error "Error receiving email at " + Time.now.to_s + "::: " + e.message
              end
            end
          end
          return email_queue
        end
      end
    rescue TimeoutError
      if(retrycount < 5)
        retrycount+=1
        retry
      else
        #logger.info("ERROR Timeout error in poll_mail attempt #" + retrycount.to_s)
        nil
      end
    end  
  rescue Exception => exception
    #SystemNotifier.deliver_exception_notification(exception)
    #logger.info("Error in poll_mail")
    #logger.info(exception.class.to_s + " " + exception.message.to_s + " " + exception.backtrace.to_s) 
  end

  def receive(email)
    email_hash={:email => email}
    attlist=[]
    if email.has_attachments?
      email.attachments.each do |a|
        attlist << a
      end
    end
    email_hash[:attachments] = attlist
    return email_hash
  end
end
